package org.magicsoft.office.excel.impt;

import java.sql.Connection;
import java.util.List;

import org.magicsoft.office.db.DatabaseType;
import org.magicsoft.office.db.DatabaseUtils;
import org.magicsoft.office.excel.model.Reference;
import org.magicsoft.office.excel.model.Sheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ParentIdUpdater {

	private static final Logger logger = LoggerFactory.getLogger(ParentIdUpdater.class);

	public void update(Sheet sheet, Connection conn, DatabaseType databaseType) {
		StringBuilder sqlBuilder;
		List<Reference> references = sheet.getReferences();
		for (Reference reference : references) {
			// mapping column不等于空说明是一个自关联。
			if (reference.getMappingColumn() != null) {
				sqlBuilder = new StringBuilder();
				sqlBuilder.append("update ");
				sqlBuilder.append(reference.getColumn().getBindTable().getTableName());
				sqlBuilder.append(" set (");
				sqlBuilder.append(reference.getColumn().getBindColumn());
				sqlBuilder.append(") = (select ");
				sqlBuilder.append(sheet.getTempTableName());
				sqlBuilder.append(".");
				sqlBuilder.append(reference.getTempTableColumn());
				sqlBuilder.append(" from ");
				sqlBuilder.append(sheet.getTempTableName());
				sqlBuilder.append(" where ");
				sqlBuilder.append(reference.getColumn().getBindTable().getTableName());
				sqlBuilder.append(".");
				sqlBuilder.append(reference.getColumn().getBindTable().getPrimaryKey().getColumn());
				sqlBuilder.append(" = ");
				sqlBuilder.append(sheet.getTempTableName());
				sqlBuilder.append(".");
				sqlBuilder.append(reference.getColumn().getBindTable().getNidColumn());
				sqlBuilder.append(")");
				String sql = DatabaseUtils.translateJoinUpdate(sqlBuilder.toString(), databaseType);
				logger.debug("update parent id sql:" + sql);
				DatabaseUtils.executeUpdate(conn, sql);
			}
		}
	}

}
